import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * <b>Comparator 的使用</b>
 * <p>
 * JDK 1.8 以上
 * </p>
 *
 * @Author Rocky Wong
 * @Date 2020/1/15 0015 10:40
 */
public class ComparatorUtils {

    public void comparing() {
        List<Employee> employees = new ArrayList<>();

        employees.sort(Comparator.comparing(e -> e.getName()));
        // 等价于下面写法
        employees.sort(Comparator.comparing(Employee::getName));

        Collections.sort(employees, Comparator.comparing(
                Employee::getName, (s1, s2) -> {
                    return s2.compareTo(s1);
                }));

        /**
         *  相反的排序规则
         */
        Collections.sort(employees, Comparator.comparing(Employee::getName).reversed());

        // 当集合中存在null元素时，可以使用针对null友好的比较器，null元素排在集合的最前面
        Collections.sort(employees, Comparator.nullsFirst(Comparator.comparing(Employee::getName)));
        Collections.sort(employees, Comparator.nullsLast(Comparator.comparing(Employee::getName)));

        // 首先使用 name 排序，紧接着在使用ege 排序
        Collections.sort(employees, Comparator.comparing(Employee::getAge).thenComparing(Employee::getName));
    }

    class Employee {
        String name;
        int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}